package com.yl.ydk.presenter.impl

import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.GridLayoutManager
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.BasePresenter
import com.yl.ydk.bean.HealthtestCategoryBean
import com.yl.ydk.presenter.contract.HealthtestCategoryContract
import com.yl.ydk.ui.activity.TestPapersActivity
import com.yl.ydk.ui.adapter.HealthtestCategoryAdapter
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class HealthtestCategoryImpl : BasePresenter<HealthtestCategoryContract.View>(),
    HealthtestCategoryContract.Presenter<HealthtestCategoryContract.View> {


    override fun getHealthtestCategory(context: Context, vararg query: String) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getHealthtestCategory(*query)
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<HealthtestCategoryBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: HealthtestCategoryBean?) {
                        dismissLoadingDialog()
                        if (t?.data != null && t.code == 1) {

                            mView?.getRvCategory()?.let {
                                val adapter = HealthtestCategoryAdapter(t.data.toMutableList())
                                val manager = GridLayoutManager(context, 4)
                                it.adapter = adapter
                                it.layoutManager = manager
                                adapter.onListItemClick(object :
                                    HealthtestCategoryAdapter.onListItemClick {
                                    override fun onListItemClick(item: HealthtestCategoryBean.Data?) {
                                        mView?.getActivity()?.let {
                                            val intent = Intent(it, TestPapersActivity::class.java)
                                            intent.putExtra("data", item?.title)
                                            intent.putExtra("type",item?.id)
                                            it.startActivityIn(intent, it)
                                        }
                                    }
                                })
                            }

                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }

}